﻿using SqlPerfomance.V2.DAL;
using SqlPerfomance.V2.DomainModel.Enums;
using SqlPerfomance.V2.DomainModel.Models;
using SqlPerfomance.V2.WpfClient.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace SqlPerfomance.V2.WpfClient
{
	/// <summary>
	/// Interaction logic for NestedSet.xaml
	/// </summary>
	public partial class NestedSet : Window
	{
		public NestedSet(ConnectionStrings connectionString)
		{
			InitializeComponent();

			var nsRepo = new NestedSetTreeRepository();
			var tree = nsRepo.GetNestedSetData(connectionString, AppSettingsHelper.NsTableName).ToList();

			var treeView = CreateTree(tree);
			trvMenu.Items.Add(treeView);

		}

		private NsTreeViewNode CreateTree(List<NestedSetTreeExtensionNode> tree)
		{
			var root = tree.Where(t => t.ParentId == 0).First();
			NsTreeViewNode treeView = new NsTreeViewNode(root.Id, (long)root.ParentId, root.Name, root.Level, root.Lft, root.Rgt);
			tree.Remove(root);
			GetTreeViewData(treeView, tree);
			return treeView;
		}

		private void GetTreeViewData(NsTreeViewNode treeView, List<NestedSetTreeExtensionNode> tree)
		{
			var children = tree.Where(t => t.ParentId == treeView.Id).ToList();
			for (int i = 0; i < children.Count; i++)
			{
				var child = new NsTreeViewNode(children[i].Id, (long)children[i].ParentId, children[i].Name, children[i].Level, children[i].Lft, children[i].Rgt);
				treeView.Children.Add(child);
				GetTreeViewData(child, tree);
			}
		}
	}
}
